import {useEffect ,useState} from "react"
import useGetUserInfo from "./useGetUserInfo"
import { useRequest } from "ahooks"
import {getUserInfo} from '../services/user'
import { useDispatch } from "react-redux"
import { loginReducer } from "../store/userReducer"

function useLoadUserData(){
  const dispatch = useDispatch()
  const [waitingUserData,setWaitingUserData] = useState(true)

  // axios获取用户信息
  const {run} = useRequest(getUserInfo,{
    manual:true,
    onSuccess(res){
      const {username,nickname} = res
      dispatch(loginReducer({username,nickname})) // 存储到redux中
    },
    onFinally(){
      setWaitingUserData(false)
    }
  })

  // 判断当前redux中是否有用户信息
  const {username} = useGetUserInfo()
  useEffect(()=>{
    if(username){
      // 如果redux中有用户信息就不需要再请求了
      setWaitingUserData(false)
      return
    }
    run() // 如果redux中没有用户信息就请求用户信息
  },[username])

  return {waitingUserData}
}
export default useLoadUserData